using System;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;

[RequireComponent(typeof(TMP_Text))]
public class RichTextUguiLinkSupport : MonoBehaviour, IPointerClickHandler
{
    private TMP_Text text;
    private void Awake()
    {
        text = GetComponent<TMP_Text>();
    }

    private Action<string> onclickEvent = null;
    public void RegisterClickEvent(Action<string> onclick)
    {
        onclickEvent = onclick;
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        if (text == null)
        {
            return;
        }

        var linkIndex = TMP_TextUtilities.FindIntersectingLink(text, Input.mousePosition, null);
        var link = text.textInfo.linkInfo[linkIndex].GetLinkID();

        if (link.StartsWith("\"") && link.EndsWith("\""))
        {
            link.Substring(1, link.Length - 2);
        }
        if (onclickEvent == null)
        {
            Application.OpenURL(link);
        }
        else
        {
            onclickEvent.Invoke(link);
        }
    }
}
